/**
 * 数据字典过滤器
 */
app.filter('dictionaryFiter', ["Dictionary", function (Dictionary) {
    return function (value, key) {
        if (!key) {
            return "";
        }
        var arrary = Dictionary.DictionaryItems[key];
        if (arrary) {
            for (var i = 0; i < arrary.length; i++) {
                var entity = arrary[i];
                var tmp = value;
                if (entity.value == tmp) {
                    return entity.label;
                }
            }
        }
        return "";
    };
}]);

app.service('Dictionary', ['$rootScope', '$http', '$q', '$localStorage', '$sessionStorage', function ($rootScope, $http, $q, $localStorage, $sessionStorage) {

    var Dictionary = {};
    var DictionaryItems = {};

    /**
     * 查询权限相关信息
     * @returns {d.promise|promise|AnimateRunner.promise|qFactory.Deferred.promise}
     */
    Dictionary.load = function () {
        var deferred = $q.defer();
        if (!$sessionStorage['sys_dictionary']) {
            $http.get('system/dictionary/listAll.do').success(function (res) {
                if(res.data) {
                	$sessionStorage['sys_dictionary'] = res.data;
                	Dictionary.dictionaryConfig(res.data, deferred);
                }
            });
        } else {
            Dictionary.dictionaryConfig($sessionStorage['sys_dictionary'], deferred);
        }
        return deferred.promise;
    }

    Dictionary.dictionaryConfig = function (items, deferred) {
        var ds = {};
        // 组装数据字典
        for (var i = 0; i < items.length; i++) {
            if (!ds[items[i].type]) {
                ds[items[i].type] = [];
            }
            var dvalue = items[i].value;
            if (items[i].dataType == 'boolean') {
                dvalue = ('true' === dvalue ? true : false);
            } else if (items[i].dataType == 'int') {
                dvalue = parseInt(dvalue);
            }
            ds[items[i].type].push({
                "label": items[i].label,
                "value": dvalue
            });
        }
        Dictionary.DictionaryItems = ds;
        $rootScope.dictionary = ds;
        deferred.resolve('');
    }

    /**
     * 获取数据字典中全部内容
     * @returns {*}
     */
    Dictionary.getDictionary = function () {
        return DictionaryItems;
    }


    return Dictionary;
}]);